﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.Linq.SqlClient;

public partial class User_Payment : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected decimal getMonthAmount()
    {
        int contractId = getContractId();
        Contract selectedContract = getContract(contractId);
        if (selectedContract != null)
        {
            decimal amount = (selectedContract.Amount - getPayedMainAmount()) / (selectedContract.TermLength - getMonthCountPayment());
            return amount;
        }
        return -1;
    }

    protected decimal getPayedMainAmount()
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == getContractId() select payment;
        decimal payedAmount = 0;
        foreach (ContractPayment contractPayment in payments)
        {
            payedAmount += contractPayment.MainAmount;
        }
        return payedAmount;
    }

    protected decimal getPayedPercentageAmount()
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == getContractId() select payment;
        decimal payedAmount = 0;
        foreach (ContractPayment contractPayment in payments)
        {
            payedAmount += contractPayment.PercentageAmount;
        }
        return payedAmount;
    }

    protected double getMonthCreditPercentage()
    {
        Contract contract = getContract(getContractId());
        var creditCurrencies = from creditCurrency in db.CreditCurrencies
                               where creditCurrency.CreditId == contract.CreditId &&
                                   creditCurrency.CurrencyId == contract.CurrencyId
                               select creditCurrency;
        return creditCurrencies.First().Percentage / 12;
    }

    protected int getMonthCountFromLastPayment()
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == getContractId() select payment;
        Contract contract = getContract(getContractId());
        DateTime maxDate = contract.CreationDate;
        foreach (ContractPayment contractPayment in payments)
        {
            if (contractPayment.Date > maxDate)
            {
                maxDate = contractPayment.Date;
            }
        }
        return SqlMethods.DateDiffMonth(maxDate, DateTime.Now);
    }

    protected int getMonthCountPayment()
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == getContractId() select payment;
        Contract contract = getContract(getContractId());
        DateTime maxDate = contract.CreationDate;
        foreach (ContractPayment contractPayment in payments)
        {
            if (contractPayment.Date > maxDate)
            {
                maxDate = contractPayment.Date;
            }
        }
        return SqlMethods.DateDiffMonth(contract.CreationDate, maxDate);
    }

    protected Contract getContract(int contractId)
    {
        var contracts = from contract in db.Contracts where contract.ContractId == contractId select contract;
        if (contracts.Count() > 0)
        {
            return contracts.First();
        }
        return null;
    }

    protected int getContractId()
    {
        string contractId = null;
        if (Session["contractId"] != null)
        {
            contractId = Session["contractId"].ToString();
            return Convert.ToInt32(contractId);
        }
        return -1;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("User"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        Contract selectedContract = getContract(getContractId());
        if (!selectedContract.Credit.AdvancedRepayment)
        {
            Amount.Enabled = false;
            int paymentCounts = getMonthCountPayment();
            int maxPaymentCountsForToday = SqlMethods.DateDiffMonth(selectedContract.CreationDate, DateTime.Now);
            if (paymentCounts >= maxPaymentCountsForToday)
            {
                PayButton.Enabled = false;
            }
        }
        decimal paymentAmount = Math.Round((getMonthAmount() + (selectedContract.Amount - getPayedMainAmount()) * (decimal)(getMonthCreditPercentage() / 100)) * getMonthCountFromLastPayment(), 2);
        if (Amount.Text == "0")
        {
            Amount.Text = paymentAmount.ToString();
        }
    }

    protected void PayButton_Click(object sender, EventArgs e)
    {
        Contract selectedContract = getContract(getContractId());
        var userBankAccounts = from bankAccount in db.BankAccountCompanies
                               where bankAccount.CompanyId == selectedContract.CompanyId &&
                                   bankAccount.BankAccount.CurrencyId == selectedContract.CurrencyId
                               select bankAccount;
        if (userBankAccounts.Count() == 0)
        {
            ErrorLabel.Text = "Нет счёта в данной валюте";
            return;
        }
        decimal percentageAmount = (selectedContract.Amount - getPayedMainAmount()) * (decimal)(getMonthCreditPercentage() / 100) * getMonthCountFromLastPayment();
        if (percentageAmount > Convert.ToDecimal(Amount.Text))
        {
            ErrorLabel.Text = "Необходимо погасить проценты по кредиту.";
            return;
        }
        if (getPayedMainAmount() + (Convert.ToDecimal(Amount.Text) - percentageAmount) > selectedContract.Amount)
        {
            ErrorLabel.Text = "Максимальная сумма: " + (selectedContract.Amount - getPayedMainAmount() + percentageAmount).ToString() + " "
                + selectedContract.Currency.Name;
            return;
        }
        if (userBankAccounts.First().BankAccount.Amount > Convert.ToDecimal(Amount.Text))
        {
            var bankAccountsMain = from bankAccount in db.BankAccountBanks where bankAccount.BankAccount.CurrencyId == selectedContract.CurrencyId && bankAccount.TypeId == 0 select bankAccount;
            var bankAccountsPercentage = from bankAccount in db.BankAccountBanks where bankAccount.BankAccount.CurrencyId == selectedContract.CurrencyId && bankAccount.TypeId == 1 select bankAccount;
            if (bankAccountsMain.Count() == 0 || bankAccountsPercentage.Count() == 0)
            {
                ErrorLabel.Text = "Оплата только наличными.";
                return;
            }
            userBankAccounts.First().BankAccount.Amount -= Convert.ToDecimal(Amount.Text);
            bankAccountsPercentage.First().BankAccount.Amount += percentageAmount;
            bankAccountsMain.First().BankAccount.Amount = bankAccountsMain.First().BankAccount.Amount + (Convert.ToDecimal(Amount.Text) - percentageAmount);
        }
        else
        {
            ErrorLabel.Text = "Недостаточно средств на счету";
            return;
        }
        ContractPayment contractPayment = new ContractPayment();
        contractPayment.ConractId = selectedContract.ContractId;
        contractPayment.Date = DateTime.Now;
        contractPayment.PercentageAmount = percentageAmount;
        contractPayment.MainAmount = Convert.ToDecimal(Amount.Text) - percentageAmount;
        contractPayment.CurrencyId = selectedContract.CurrencyId;
        db.ContractPayments.InsertOnSubmit(contractPayment);
        db.SubmitChanges();
        if (getPayedMainAmount() >= selectedContract.Amount)
        {
            selectedContract.StatusId = 2;
            db.SubmitChanges();
        }
        Response.Redirect("~/User/ContractInformation.aspx");
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            Contract selectedContract = getContract(getContractId());
            e.Row.Cells[4].Text = getPayedPercentageAmount().ToString();
            e.Row.Cells[5].Text = getPayedMainAmount().ToString();
            e.Row.Cells[6].Text = (getPayedPercentageAmount() + getPayedMainAmount()).ToString();
        }
    }
}